import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from '@/stores/user'
import { addCartAPI } from '@/apis/cartAPI' // 引入添加购物车的API
import { getCartByUserIdAPI } from '@/apis/cartAPI' // 引入根据用户ID获取购物车列表的API
import { deleteCartAPI } from '@/apis/cartAPI' // 引入删除购物车的API

export const useCartStore = defineStore("cart", () =>{



     //1.定义state - cartList
     const cartList = ref([]); // 购物车列表
     //2.定义action - cartList
    const addCart = async (goods) => {


        //获取用户store
        const userStore = useUserStore();
        //获取用户是否登录状态
        const isLogin = computed(() => userStore.userInfo?.userInfoVO?.token);
        if(isLogin.value){
            goods.userId = userStore.userInfo.userInfoVO.id; //设置用户ID
            //调用添加购物车的API
            await addCartAPI(goods);
            //获取购物车列表数据
            const res = await getCartByUserIdAPI(userStore.userInfo.userInfoVO.id);
            cartList.value = res.data; //更新购物车列表
        }else{
            //添加购物车操作
            //已添加过的商品数量加1
            //没有添加过的直接push

            const item = cartList.value.find(item => item.productId === goods.productId)
            if(item){
                item.num = item.num + goods.num;
            }else{
                cartList.value.push(goods);
            }
        }


    }

    //删除购物车
    const delCart = async (productId) =>{
         //获取用户store
        const userStore = useUserStore();
        //获取用户是否登录状态
        const isLogin = computed(() => userStore.userInfo?.userInfoVO?.token);
        if(isLogin.value){
            console.log('已登录，调用删除购物车接口');
            //调用删除购物车的API
            await deleteCartAPI(userStore.userInfo.userInfoVO.id,productId);
            //获取购物车列表数据
            const res = await getCartByUserIdAPI(userStore.userInfo.userInfoVO.id);
            cartList.value = res.data; //更新购物车列表
        }else{
            //查找要删除商品在cartList中的索引
            const index = cartList.value.findIndex(item => item.productId === productId);
            cartList.value.splice(index, 1); //删除该商品
        }

    }

    //3.计算总的数量
    const totalCount = computed(() => {
       return  cartList.value.reduce((total,item) => total + item.num,0)
    })

    //4.计算总价
    const totalPrice = computed(() => {
       return  cartList.value.reduce((total,item) => total + item.price * item.num,0)
    })

    //5.单选功能
    const signleCheck = (selected,productId) => {
        console.log(selected);

        const item = cartList.value.find((item) => item.productId === productId)
        if(item){
            item.selected = selected; //更新选中状态
        }
        // 单选框选中逻辑
    }

    //6.是否全部选中
    const isAll = computed(() => {
       return cartList.value.length > 0 && cartList.value.every(item => item.selected);
    })

    //7.全选功能
    const allCheck = (selected) => {
        cartList.value.forEach(item => {
            item.selected = selected;
        })
    }

    //8.已选中商品数量
    const selectedCount = computed(() => {
        return cartList.value.filter(item => item.selected).length;
    })

    //9.已选中商品的总价
    const selectedTotalPrice = computed(() => {
        return cartList.value.filter(item => item.selected).reduce((total, item) => total + item.price * item.num, 0);
    })

    //10.清除购物车
    const clearCart = () => {
        cartList.value = [];
    }

    //11.获取所有选中的商品
    const selectedItems = computed(() => {
        return cartList.value.filter(item => item.selected);
    })

    //12.修改cartList的值
    const setCartList = (list) => {
        cartList.value = list;
    }
    return {
        cartList,
        totalCount,
        totalPrice,
        isAll,
        selectedCount,
        selectedTotalPrice,
        selectedItems,
        delCart,
        addCart,
        signleCheck,
        allCheck,
        clearCart,
        setCartList

    }
  },
  {
       persist:true
 })
